package com.tcs.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.tcs.model.Article;
import com.tcs.model.Requisition;
import com.tcs.model.RequisitionClose;
import com.tcs.model.RequisitionDetail;
import com.tcs.model.User;
import com.tcs.service.ArticleService;
import com.tcs.service.RequisitionService;

@Controller
@Scope
public class RequisitionController {

	@Resource
	private RequisitionService requisitionService;

	@Resource
	private ArticleService articleService;

	@Resource
	private RequisitionStateController requisitionStateController;


	/*
	 * Muestra el listado de Pedido Cerrados de todos los clientes para uso del
	 * ADMINISTRADOR
	 */
	@RequestMapping(value = "/requisitionListClosedAdmin", method = RequestMethod.GET)
	public ModelAndView requisitionListClosedAdmin() {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("requisitions", requisitionService.listRequisitionClose());
		return new ModelAndView("requisitionListClosedAdmin", model);

	}

	/*
	 * Agrega articulos a un pedido Abierto PARA CLIENTE
	 */
	@RequestMapping(value = "/addReqDetail", method = RequestMethod.GET)
	public ModelAndView addRequisitionDetail(
			@ModelAttribute("requisitiondetail") RequisitionDetail requisitionDetail,
			@ModelAttribute("requisition") Requisition requisition,
			@ModelAttribute("article") Article article, BindingResult result,
			HttpServletRequest request) {
		request.setAttribute(
				"requisition",
				requisitionService.getRequisition(Integer.valueOf(
						request.getParameter("id")).intValue()));
		// request.setAttribute("requisitions",
		// requisitionService.listRequisition());
		request.setAttribute("articles", articleService.listArticles());
		Map<String, Object> model = new HashMap<String, Object>();
		model.put(
				"requisitionInfo",
				requisitionService.getRequisition(Integer.valueOf(
						request.getParameter("id")).intValue()));
		model.put(
				"requisitionsDetail",
				requisitionService.listRequisitionDetailByReq(Integer.valueOf(
						request.getParameter("id")).intValue()));
		return new ModelAndView("addRequisitionDetail", model);

	}

	/*
	 * Guarda articulos a un pedido Abierto PARA CLIENTE
	 */
	@RequestMapping(value = "/saveRequisitionDetail", method = RequestMethod.POST)
	public ModelAndView saveRequisitionDetail(
			@ModelAttribute("requisitiondetail") RequisitionDetail requisitionDetail,
			BindingResult result, HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		int idReq = Integer.valueOf(request.getParameter("requisition"));
		int idArt = Integer.valueOf(request.getParameter("article"));
		requisitionDetail.setArticle(articleService.getArticle(idArt));
		requisitionDetail.setRequisition(requisitionService
				.getRequisition(idReq));
		requisitionDetail.setRequisitionDetailDate(new Date());
		requisitionService.addRequisitionDetail(requisitionDetail);
		return new ModelAndView("redirect:/addReqDetail.html?id=" + idReq);
	}

	/*
	 * Lista el detalle de articulos que posee un pedido ABIERTO (USO DE CLIENTE
	 * Y ADMIN)
	 */
	@RequestMapping(value = "/listReqDetailByReq", method = RequestMethod.GET)
	public ModelAndView listReqDetailByReq(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put(
				"requisitionInfo",
				requisitionService.getRequisition(Integer.valueOf(
						request.getParameter("id")).intValue()));
		model.put(
				"requisitionsDetail",
				requisitionService.listRequisitionDetailByReq(Integer.valueOf(
						request.getParameter("id")).intValue()));
		return new ModelAndView("reqDetailList", model);
	}

	/*
	 * Lista el detalle de articulos que posee un pedido CERRADO (USO DE CLIENTE
	 * Y ADMIN)
	 */
	@RequestMapping(value = "/listReqDetailCloseByReq", method = RequestMethod.GET)
	public ModelAndView listReqDetailCloseByReq(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put(
				"requisitionInfo",
				requisitionService.getRequisition(Integer.valueOf(
						request.getParameter("id")).intValue()));
		model.put("requisitionsDetail", requisitionService
				.listRequisitionDetailCloseByReq(Integer.valueOf(
						request.getParameter("id")).intValue()));
		return new ModelAndView("reqDetailCloseList", model);
	}

	

	/*
	 * Muestra el listado de pedidos ABIERTOS que tiene un cliente
	 */
	@RequestMapping(value = "/requisitionListOpenByUser", method = RequestMethod.GET)
	public ModelAndView requisitionListOpenByUser(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("requisitions", requisitionService
				.listRequisitionByUserByState(
						Integer.valueOf(request.getParameter("id")).intValue(),
						1));
		return new ModelAndView("requisitionListOpenByUser", model);
	}

	/*
	 * 
	 * Muestra el listado de pedidos CERRADOS que tiene un cliente
	 */

	@RequestMapping(value = "/requisitionListClosedByUser", method = RequestMethod.GET)
	public ModelAndView requisitionListClosedByUser(HttpServletRequest request) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("requisitions", requisitionService
				.listRequisitionByUserByState(
						Integer.valueOf(request.getParameter("id")).intValue(),
						2));
		return new ModelAndView("requisitionListClosedByUser", model);
	}

	/*
	 * Creo y guardo un nuevo Pedido. Por defecto su estado es Abierto
	 */
	@RequestMapping(value = "/saveRequisition", method = RequestMethod.POST)
	public ModelAndView saveRequisition(
			@ModelAttribute(" order") Requisition requisition,
			BindingResult result, HttpServletRequest request) {
		requisition
				.setUser((User) request.getSession().getAttribute("usuario"));
		requisition.setRequisitionDate(new Date());
		requisition.setState(requisitionStateController.getState(1));
		requisitionService.addRequisition(requisition);
		int x = requisition.getRequisitionId();

		request.getSession().getAttribute("administrador");
		// llamo al metodo para enviar el mail
		SendMail.sendMailNewRequisition(requisition.getUser(), requisition,
				request);
		return new ModelAndView("redirect:/addReqDetail.html?id=" + x);

	}

	/*
	 * Dado un pedido Abierto, lo pasa a Cerrado para CLIENTES
	 */
	@RequestMapping(value = "/closeRequisition", method = RequestMethod.POST)
	public ModelAndView closeRequisition(HttpServletRequest request) {
		Date dateNow = new Date();
		int reqID = Integer.valueOf(request.getParameter("id"));
		Requisition req = requisitionService.getRequisition(reqID);
		req.setState(requisitionStateController.getState(2));
		req.setRequisitionDate(dateNow);
		requisitionService.addRequisition(req);

		List<RequisitionDetail> listReqDetail = requisitionService
				.listRequisitionDetailByReq(Integer.valueOf(request
						.getParameter("id")));
		RequisitionClose rc = new RequisitionClose();
		// Recorro todo el detalle del pedido y lo paso a detalle de pedido
		// cerrado
		for (int i = 0; i < listReqDetail.size(); i++) {
			rc.setArticle(listReqDetail.get(i).getArticle().getArticleName());
			rc.setBrand(listReqDetail.get(i).getArticle().getArticleBrand()
					.getBrandName());
			rc.setPrice(listReqDetail.get(i).getArticle().getArticlePrice());
			rc.setRequisition(listReqDetail.get(i).getRequisition());
			rc.setRequisitionDetailDate(listReqDetail.get(i)
					.getRequisitionDetailDate());
			rc.setRequisitionDetailTotal(listReqDetail.get(i)
					.getRequisitionDetailTotal());
			requisitionService.addRequisitionClose(rc);
			requisitionService.deleteRequisitionDetail(listReqDetail.get(i));
		}

		// enviamos el mail
		SendMail.sendMailCloseRequisition(req.getUser(), requisitionService
				.listRequisitionDetailCloseByReq(req.getRequisitionId()));
		// volvemos al listado de pedidos abiertos
		return new ModelAndView(
				"redirect:/requisitionListClosedByUser.html?id="
						+ req.getUser().getUserId());
	}

	/*
	 * Dado un pedido Abierto, lo pasa a Cerrado. Por medio de un link GET
	 * (CLIENTES)
	 */
	@RequestMapping(value = "/closeRequisitionLink", method = RequestMethod.GET)
	public ModelAndView closeRequisitionLink(HttpServletRequest request) {
		Date dateNow = new Date();
		int reqID = Integer.valueOf(request.getParameter("id"));
		Requisition req = requisitionService.getRequisition(reqID);
		req.setState(requisitionStateController.getState(2));
		req.setRequisitionDate(dateNow);
		requisitionService.addRequisition(req);

		List<RequisitionDetail> listReqDetail = requisitionService
				.listRequisitionDetailByReq(Integer.valueOf(request
						.getParameter("id")));
		RequisitionClose rc = new RequisitionClose();
		// Recorro todo el detalle del pedido y lo paso a detalle de pedido
		// cerrado
		for (int i = 0; i < listReqDetail.size(); i++) {
			rc.setArticle(listReqDetail.get(i).getArticle().getArticleName());
			rc.setBrand(listReqDetail.get(i).getArticle().getArticleBrand()
					.getBrandName());
			rc.setPrice(listReqDetail.get(i).getArticle().getArticlePrice());
			rc.setRequisition(listReqDetail.get(i).getRequisition());
			rc.setRequisitionDetailDate(listReqDetail.get(i)
					.getRequisitionDetailDate());
			rc.setRequisitionDetailTotal(listReqDetail.get(i)
					.getRequisitionDetailTotal());
			requisitionService.addRequisitionClose(rc);
			requisitionService.deleteRequisitionDetail(listReqDetail.get(i));
		}

		// enviamos el mail
		SendMail.sendMailCloseRequisition(req.getUser(), requisitionService
				.listRequisitionDetailCloseByReq(req.getRequisitionId()));
		// volvemos al listado de pedidos abiertos
		return new ModelAndView(
				"redirect:/requisitionListClosedByUser.html?id="
						+ req.getUser().getUserId());
	}

	/*
	 * Dado un pedido Anulamos el mismo
	 */
	@RequestMapping(value = "/annulRequisition", method = RequestMethod.GET)
	public ModelAndView annulRequisition(HttpServletRequest request) {
		Requisition req = requisitionService.getRequisition(Integer
				.valueOf(request.getParameter("id")));
		int x = new Long(req.getUser().getUserId()).intValue();
		String res = "";
		User usuario = (User) request.getSession().getAttribute("usuario");

		// Anulo un pedido abierto
		if (req.getState().getStateType() == 1) {

			req.setState(requisitionStateController.getState(3));
			requisitionService.addRequisition(req);

			if (usuario.getPermission().getPermissionId() == 1) {
				// soy administrador, vuelvo al listado abierto de pedidos de
				// mis clientes
				res = "redirect:/listOfRequisitionByDate.html";
			} else {
				// soy cliente, vuelvo al listado de pedidos abiertos
				res = "redirect:/requisitionListOpenByUser.html?id=" + x;

			}

		}
		// Anulo un pedido cerrado
		else if (req.getState().getStateType() == 2) {

			// check solo si no pasaron mas de 24hs
			Date dateNow = new Date();
			long requisitionDate = req.getRequisitionDate().getTime() + 86400000;
			if (requisitionDate >= dateNow.getTime()) {
				req.setState(requisitionStateController.getState(3));
				requisitionService.addRequisition(req);
				res = "redirect:/requisitionListClosedByUser.html?id=" + x;
			}

		}
		// llamo al metodo para enviar el mail
		SendMail.sendMailCanceledRequisition(req.getUser(), req, request);
		return new ModelAndView(res);

	}

	@RequestMapping(value = "/deleteRequisitionDetail", method = RequestMethod.GET)
	public ModelAndView deleteRequisitionDetail(HttpServletRequest request) {
		requisitionService.deleteRequisitionDetail(requisitionService
				.getRequisitionDetail(Integer.valueOf(request
						.getParameter("idRD"))));
		int idRe = Integer.valueOf(request.getParameter("id"));
		return new ModelAndView("redirect:/addReqDetail.html?id=" + idRe);
	}

	@RequestMapping(value = "/listOfRequisitionByDate", method = RequestMethod.GET)
	public ModelAndView listRequisitionDate(HttpServletRequest request)
			throws ParseException {
		String str_date = "11/11/07";
		DateFormat formatter;
		Date date;
		formatter = new SimpleDateFormat("dd/mm/yyyy");
		date = (Date) formatter.parse(str_date);
		Date mydate = new Date();
		long sinceDate = date.getTime() / 1000;
		long toDate = mydate.getTime() / 1000;

		if (request.getParameter("sinceDate") != null
				&& request.getParameter("toDate") != null) {

			sinceDate = Long.parseLong(request.getParameter("sinceDate"));
			toDate = Long.parseLong(request.getParameter("toDate"));
		}

		Map<String, Object> model = new HashMap<String, Object>();
		model.put("requisitions",
				requisitionService.listofRequisitionbyDate(sinceDate, toDate));
		return new ModelAndView("requisitionListOpenByDateAdmin", model);
	}

	@RequestMapping(value = "/listOfRequisitionOpen", method = RequestMethod.GET)
	public ModelAndView listOfRequisitionOpen(HttpServletRequest request)
			throws ParseException {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("requisitions", requisitionService.listRequisitionOpen());
		return new ModelAndView("requisitionClientsToContact", model);
	}
}
